#ifndef __TRAPDOOR_BLOCK_HPP__
#define __TRAPDOOR_BLOCK_HPP__

#include "Blocks/TrapdoorBlock.h"
#include "Components/ComponentMiner.h"
#include "Components/ComponentCreature.h"
#include "Components/ComponentCreatureModel.h"

namespace PocketSurvival
{
	TrapdoorBlock::TrapdoorBlock()
	{
		addInheritance(this);
	}

    BlockPlacementData TrapdoorBlock::getPlacementValue(ComponentMiner *componentMiner, int32_t value, const TerrainRaycastResult &raycastResult)
    {
		int32_t rotation = 0;
		bool upsideDown;
		if (raycastResult.cellFace.face < 4)
		{
			rotation = raycastResult.cellFace.face;
			upsideDown = (raycastResult.hitPoint().posY - raycastResult.cellFace.point.posY > 0.5f);
		}
		else
		{
			Vector3 forward = componentMiner->componentCreature->componentCreatureModel->getEyeRotation().toMatrix().getForward();

			float numBuff[4] = {
				Vector3::Dot(forward, FastVector3::UnitZ),
				Vector3::Dot(forward, FastVector3::UnitX),
				Vector3::Dot(forward, FastVector3::DecUnitZ),
				Vector3::Dot(forward, FastVector3::DecUnitX)
			};
			uint32_t targetIndex = MathUtils::MaxIndex<float>(numBuff, 4);
			switch (targetIndex)
			{
			case 0:
				rotation = 2;
				break;
			case 1:
				rotation = 3;
				break;
			case 2:
				rotation = 0;
				break;
			case 3:
				rotation = 1;
				break;
			}
			upsideDown = (raycastResult.cellFace.face == 5);
		}
		int32_t data = SetOpen(SetRotation(SetUpsideDown(0, upsideDown), rotation), false);
		BlockPlacementData result;
		result.value = Terrain::ReplaceData(Terrain::ReplaceContents(0, getIndex()), data);
		result.cellFace = raycastResult.cellFace;
		return result;
    }

    const std::vector<BoundingBox> &TrapdoorBlock::getCustomCollisionBoxes(int32_t value)
    {
		int32_t num = Terrain::ExtractData(value);
		if (num < 16)
		{
			return BlockConstans::trapdoorCollisionBoxes[num];
		}
		return BlockConstans::defaultCollisionBoxes;
    }

} // namespace PocketSurvival


#endif
